package com.zycfc.zsf.boot.util.text;

import org.apache.commons.collections.*;
import org.apache.commons.collections.bidimap.*;
import java.util.*;
import org.slf4j.*;

public interface UnifiedCreditCodeUtils
{
    public static final Logger logger = LoggerFactory.getLogger((Class)UnifiedCreditCodeUtils.class);
    public static final String baseCode = "0123456789ABCDEFGHJKLMNPQRTUWXY";
    public static final char[] baseCodeArray = "0123456789ABCDEFGHJKLMNPQRTUWXY".toCharArray();
    public static final int[] wi = { 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28 };
    
    default boolean validateUnifiedCreditCode(final String unifiedCreditCode) {
        if (StringUtils.isEmpty(unifiedCreditCode) || unifiedCreditCode.length() != 18) {
            return false;
        }
        final Map<Character, Integer> codes = (Map<Character, Integer>)generateCodes();
        int parityBit;
        try {
            parityBit = getParityBit(unifiedCreditCode, codes);
        }
        catch (Exception e) {
            return false;
        }
        return parityBit == codes.get(unifiedCreditCode.charAt(unifiedCreditCode.length() - 1));
    }
    
    default BidiMap generateCodes() {
        final BidiMap codes = (BidiMap)new TreeBidiMap();
        for (int i = 0; i < "0123456789ABCDEFGHJKLMNPQRTUWXY".length(); ++i) {
            codes.put((Object)UnifiedCreditCodeUtils.baseCodeArray[i], (Object)i);
        }
        return codes;
    }
    
    default int getParityBit(final String unifiedCreditCode, final Map<Character, Integer> codes) {
        final char[] businessCodeArray = unifiedCreditCode.toCharArray();
        int sum = 0;
        for (int i = 0; i < 17; ++i) {
            final char key = businessCodeArray[i];
            if ("0123456789ABCDEFGHJKLMNPQRTUWXY".indexOf(key) == -1) {}
            sum += codes.get(key) * UnifiedCreditCodeUtils.wi[i];
        }
        final int result = 31 - sum % 31;
        return (result == 31) ? 0 : result;
    }
    
    default String generateOneUnifiedCreditCode() {
        final Random random = new Random();
        final StringBuilder buf = new StringBuilder();
        for (int i = 0; i < 17; ++i) {
            final int num = random.nextInt("0123456789ABCDEFGHJKLMNPQRTUWXY".length() - 1);
            buf.append("0123456789ABCDEFGHJKLMNPQRTUWXY".charAt(num));
        }
        final String code = buf.toString();
        String upperCode = code.toUpperCase();
        final BidiMap codes = generateCodes();
        final int parityBit = getParityBit(upperCode, (Map<Character, Integer>)codes);
        if (codes.getKey((Object)parityBit) == null) {
            UnifiedCreditCodeUtils.logger.debug("\u751f\u6210\u793e\u4f1a\u7edf\u4e00\u4fe1\u7528\u4ee3\u7801\u4e0d\u7b26\u5408\u89c4\u5219");
            upperCode = generateOneUnifiedCreditCode();
        }
        else {
            upperCode += codes.getKey((Object)parityBit);
        }
        return upperCode;
    }
}
